﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Cosmetic.Logic;
using Cosmetic.DataEntity;
using System.Web.UI.HtmlControls;
using System.Collections;
using Cosmetic;

namespace WebApp.Product
{
    public partial class ProductCategory : System.Web.UI.Page
    {
        private CategoryManager m_CategoryManager = new CategoryManager();
        private PlateManager PM = new PlateManager();
        private ProductManager m_ProductManager = new ProductManager();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (!string.IsNullOrEmpty(Request.QueryString["CID"]))
                {
                    BindLiteral(Request.QueryString["CID"]);
                    this.ListView6.DataSource = PM.Gethotpro();//最近销售
                    this.ListView6.DataBind();

                    string supCategoryId = m_CategoryManager.GetCategoryById(new Guid(Request.QueryString["CID"])).SupCategoryId.ToString();
                    ShowCategory(supCategoryId);
                    ShowSubCategory(Request.QueryString["CID"].ToString());

                    if (!string.IsNullOrEmpty(Request.QueryString["SID"]))
                    {


                    }
                    //else
                    //{
                    //    string supCategoryId = m_CategoryManager.GetCategoryById(new Guid(Request.QueryString["CID"])).SupCategoryId.ToString();
                    //    ShowCategory(supCategoryId);
                    //    ShowSubCategory(Request.QueryString["CID"]);
                    //}
                    BindProduct();
                }
            }
        }
        private void BindProduct()
        {
            if (Request.QueryString["CID"] == null)
            {
                return;
            }
            List<Cosmetic.DataEntity.Product> result = new List<Cosmetic.DataEntity.Product>();
            if (Request.QueryString["SID"] == null)
            {
                result = m_ProductManager.GetProductByFirstCategory(new Guid(Request.QueryString["CID"].ToString()));
            }
            else
            {
                result = m_ProductManager.GetProductByCategory(new Guid(Request.QueryString["SID"].ToString()));
            }

            if (Request.QueryString["Price"] != null)
            {
                string price = Request.QueryString["Price"].ToString();
                if (price == "1")
                {//1-99
                    result = result.Where(c => c.eprice >= 1 && c.eprice <= 99).ToList();
                    this.lkBtnPrice1.Style.Add("color", "#FF7D01");
                }
                if (price == "2")
                {//100-500
                    result = result.Where(c => c.eprice >= 100 && c.eprice <= 500).ToList();
                    this.lkBtnPrice2.Style.Add("color", "#FF7D01");
                }
                if (price == "3")
                {//>500
                    result = result.Where(c => c.eprice > 500).ToList();
                    this.lkBtnPrice3.Style.Add("color", "#FF7D01");
                }
                if (price == "4")
                {//大型 //==0.01 ,价格显示为咨询
                    result = result.Where(c => c.eprice == decimal.Parse("0.01")).ToList();
                    this.lkBtnPrice4.Style.Add("color", "#FF7D01");
                }
            }
            this.lvProductByCategory.DataSource = result;
            this.lvProductByCategory.DataBind();
        }

        private void BindLiteral(string categoryId)
        {
            Category cate = m_CategoryManager.GetCategoryById(new Guid(categoryId));
            this.HLSupCategory.Text = cate.SupCategory.Name;
            this.HLSupCategory.NavigateUrl = "~/Product/ProductTopCategory.aspx?CID=" + cate.SupCategoryId.ToString();

            if (!string.IsNullOrEmpty(Request.QueryString["SID"]))
            {
                //三级目录
                //title
                Category subcate = m_CategoryManager.GetCategoryById(new Guid(Request.QueryString["SID"]));
                //this.Title = string.Format("【{0}专区】_{0}最新价格,评价,品牌,图片,买{0},首选日花商城！", subcate.Name);
                //description
                //this.Page.MetaDescription = string.Format("日花商城{0}专区,提供最新的{0}报价,{0}评价,{0}使用说明,{0}售后维修,商城100%正品保证,全国联保,积分兑大礼,网购{0},首选日花商城【直销,便捷,诚信！】", subcate.Name);
                //this.Page.MetaKeywords = string.Format("{0},{0}价格,{0}评价,{0}品牌,{0}图片,日花商城", subcate.Name);

                this.Title = string.Format("{0}_日花商城|我们最懂医疗保健器械", subcate.Name);
                //description
                this.Page.MetaDescription = string.Format("日花商城是专业提供{0}的家用医疗保健器械供应商，您可以在这了解{0}的最新价格、优惠促销、网友评论导购、图片等相关内容。", subcate.Name);
                this.Page.MetaKeywords = string.Format("{0}", subcate.Name);
            }
            else
            {
                //两级目录

                //title
                //this.Page.Title = string.Format("【{0}栏目】_日花商城－尽享万千正品医疗器械,医用耗材网上采购新体验!", cate.Name);
                this.Page.Title = string.Format("{0}_日花商城|我们最懂医疗保健器械", cate.Name);
                //description
                //this.Page.MetaDescription = string.Format("日花商城{0}栏目,轻松拥有性价比更高的{0}产品,商城100%正品保证,全国联保,积分兑大礼,网购{0}产品,首选日花商城【直销,便捷,诚信！】", cate.Name);
                this.Page.MetaDescription = string.Format("日花商城提供齐全的家用医疗保健器械,{0}产品全场5折,商城100%正品保证,全国联保,积分兑大礼,网购{0}产品,首选日花商城【直销,便捷,诚信！】", cate.Name);
                this.Page.MetaKeywords = string.Format("{0}", cate.Name);
            }


            this.LtlCategory.Text = cate.Name;
            this.ltlSupCategory.Text = cate.SupCategory.Name;
        }

        protected void rptCategory_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (!string.IsNullOrEmpty(Request.QueryString["CID"]))
            {
                HyperLink hla = e.Item.FindControl("hlcategory") as HyperLink;
                HiddenField hfcategoryid = e.Item.FindControl("HFCategoryId") as HiddenField;
                if (hfcategoryid.Value == Request.QueryString["CID"])
                {
                    hla.Style.Add("color", "#FF7D01");
                }
            }
        }
        private void ShowCategory(string categoryid)
        {
            string supCategoryName = ltlSupCategory.Text;
            List<Category> subs = this.m_CategoryManager.GetSubCateogoriesBySupCategory(this.m_CategoryManager.GetCategoryById(new Guid(categoryid))).OrderBy(theCategory => theCategory.Index).ToList();

            //if (string.IsNullOrEmpty(Request.QueryString["SID"]))
            //{
            //    string strsubs = string.Empty;

            //    foreach (Category item in subs)
            //    {
            //        strsubs += item.Name + ",";
            //    }
            //    strsubs += "日花商城";

            //    this.Page.MetaKeywords = supCategoryName + "," + strsubs;
            //}


            rptCategory.DataSource = subs;
            rptCategory.DataBind();
        }

        private void ShowSubCategory(string subcategoryid)
        {
            rptSubCategory.DataSource = this.m_CategoryManager.GetSubCateogoriesBySupCategory(this.m_CategoryManager.GetCategoryById(new Guid(subcategoryid))).OrderBy(theCategory => theCategory.Index);
            rptSubCategory.DataBind();
        }

        protected void rptSubCategory_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            HiddenField hfCategoryId = e.Item.FindControl("hfCagegoryId") as HiddenField;
            HyperLink hlcategory = e.Item.FindControl("HLSubCategoryId") as HyperLink;

            string upCategoryId = m_CategoryManager.GetCategoryById(new Guid(hfCategoryId.Value)).SupCategoryId.ToString();

            hlcategory.NavigateUrl = "~/Product/ProductCategory.aspx?CID=" + upCategoryId + "&SID=" + hfCategoryId.Value;

            if (!string.IsNullOrEmpty(Request.QueryString["SID"]))
            {
                if (hfCategoryId.Value == Request.QueryString["SID"])
                {
                    hlcategory.Style.Add("color", "#FF7D01");
                }
            }
        }
        public string spliteStr(string title)
        {
            if (title.Length > 10)
            {
                title = title.Substring(0, 10) + "…";
            }
            return title;
        }
        public string spliteStrs(string title)
        {
            if (title.Length > 15)
            {
                title = title.Substring(0, 15) + "…";
            }
            return title;
        }




        protected void lkBtnPrice1_Click(object sender, EventArgs e)
        {
            string NoQuery = Request.Url.ToString().Replace(Request.Url.Query.ToString(), "");
            NoQuery += "?";
            if (!string.IsNullOrEmpty(Request.QueryString["CID"]))
            {
                NoQuery += "CID=" + Request.QueryString["CID"].ToString();
            }

            if (!string.IsNullOrEmpty(Request.QueryString["SID"]))
            {
                NoQuery += "&SID=" + Request.QueryString["SID"].ToString();
            }

            NoQuery += "&Price=1";
            Response.Redirect(NoQuery);
        }

        protected void lkBtnPrice2_Click(object sender, EventArgs e)
        {
            string NoQuery = Request.Url.ToString().Replace(Request.Url.Query.ToString(), "");
            NoQuery += "?";
            if (!string.IsNullOrEmpty(Request.QueryString["CID"]))
            {
                NoQuery += "CID=" + Request.QueryString["CID"].ToString();
            }

            if (!string.IsNullOrEmpty(Request.QueryString["SID"]))
            {
                NoQuery += "&SID=" + Request.QueryString["SID"].ToString();
            }

            NoQuery += "&Price=2";
            Response.Redirect(NoQuery);
        }

        protected void lkBtnPrice3_Click(object sender, EventArgs e)
        {
            string NoQuery = Request.Url.ToString().Replace(Request.Url.Query.ToString(), "");
            NoQuery += "?";
            if (!string.IsNullOrEmpty(Request.QueryString["CID"]))
            {
                NoQuery += "CID=" + Request.QueryString["CID"].ToString();
            }

            if (!string.IsNullOrEmpty(Request.QueryString["SID"]))
            {
                NoQuery += "&SID=" + Request.QueryString["SID"].ToString();
            }

            NoQuery += "&Price=3";
            Response.Redirect(NoQuery);
        }

        protected void lkBtnPrice4_Click(object sender, EventArgs e)
        {
            string NoQuery = Request.Url.ToString().Replace(Request.Url.Query.ToString(), "");
            NoQuery += "?";
            if (!string.IsNullOrEmpty(Request.QueryString["CID"]))
            {
                NoQuery += "CID=" + Request.QueryString["CID"].ToString();
            }

            if (!string.IsNullOrEmpty(Request.QueryString["SID"]))
            {
                NoQuery += "&SID=" + Request.QueryString["SID"].ToString();
            }

            NoQuery += "&Price=4";
            Response.Redirect(NoQuery);
        }
        protected void lvProductByCategory_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            if (e.CommandName == "AddCart")
            {
                //ImageButton imgBtn = sender as ImageButton;
                Guid theGuid = new Guid(e.CommandArgument.ToString());
                Cosmetic.DataEntity.Product pif = m_ProductManager.GetProductById(theGuid);
                //if (pif.在库数量 <= 0)
                //{
                //    Page.RegisterStartupScript("openalert", "<script>alert('该商品库存不足，请至商品详细页面预订');</script>");
                //    return;
                //}
                if (pif.eprice == decimal.Parse("0.01"))
                {
                    Page.RegisterStartupScript("openalert", "<script>alert('请拨打公司的服务热线：400-6676-996进行询价！');</script>");
                    return;
                }

                Buy(theGuid);
                Response.Redirect("~/Shopping/shopCart.aspx");

                //if (Session["buycarts"] != null)
                //{

                //    Page.RegisterStartupScript("openconfirm ", " <script> if(confirm( '尊敬的用户，由于您选择的产品属于不同\\n的支付系统，所以您的购物车内原有的商\\n品会自动取消,是否继续操作？ ')){self.location='../Shopping/shopCart.htm'} else{self.location='../Shopping/shopCarts.htm'} </script> ");

                //    return;
                //}
                //else
                //{
                //    Response.Redirect("~/Shopping/shopCart.htm");
                //}
            }
        }

        private void Buy(Guid temGuid)
        {

            try
            {
                int theCount = 1;//这里默认为1;

                //add to buy cart
                if (null == Session["buycart"])
                {
                    Session["buycart"] = new Hashtable();
                }
                //加入尺寸
                if (null == Session["size"])
                {
                    Session["size"] = new Hashtable();
                }
                try
                {
                    if (((Hashtable)Session["buycart"]).Contains(temGuid.ToString()))
                    {
                        int tint = int.Parse(((Hashtable)Session["buycart"])[temGuid.ToString()].ToString());
                        ((Hashtable)Session["buycart"])[temGuid.ToString()] = (++tint).ToString();
                    }
                    else
                    {
                        ((Hashtable)Session["buycart"]).Add(temGuid.ToString(), theCount.ToString());
                    }
                    //Response.Redirect("~/Shopping/shopCart.htm");
                }
                catch (Exception)
                {
                    WebGeneric.WebMessageBox("购物篮添加失败!", this.Page);
                }
            }
            catch
            {
                WebGeneric.WebMessageBox("请正确填写购买数量!", this.Page);
            }
        }

        protected void lvProductByCategory_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            HiddenField hfePrice = e.Item.FindControl("hfePrice") as HiddenField;
            Label lbePrice = e.Item.FindControl("lbePrice") as Label;

            ImageButton btnaskprice = e.Item.FindControl("btnAskPrice") as ImageButton;
            //btnAskPrice
            //HtmlGenericControl askprice = e.Item.FindControl("AskPrice") as HtmlGenericControl;
            //HtmlGenericControl AddCart = e.Item.FindControl("AddBtn") as HtmlGenericControl;


            if (hfePrice.Value != "" && decimal.Parse(hfePrice.Value) == decimal.Parse("0.01"))
            {
                btnaskprice.Visible = true;
                lbePrice.Visible = false;
            }
            else
            {
                btnaskprice.Visible = false;
                lbePrice.Visible = true;
            }
        }

        protected void lvProductByCategory_PagePropertiesChanged(object sender, EventArgs e)
        {
            BindProduct();
        }


    }
}